package com.ha.auto_skip;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.ha.auto_skip.adapter.JumpAdapter;
import com.ha.auto_skip.bean.JumpBean;
import com.ha.auto_skip.databinding.ActivityMainBinding;
import com.ha.auto_skip.service.SaveService;
import com.ha.auto_skip.utils.InputDialog;
import com.ha.auto_skip.utils.SpacesItemDecoration;
import com.ha.auto_skip.utils.SystemDialog;
import com.xinkao.skmvp.utils.MyToast;

/**
 * 操作流程：
 * adb 设置权限
 * 设置-》无障碍中设置为启动
 */
public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;

    JumpAdapter adapter;

    /**
     * 页面数据回传
     */
    ActivityResultLauncher<Intent> mActivityResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 服务保活
//        startService(new Intent(this, SaveService.class));

        try {
            // 无障碍模式自动开启
            Settings.Secure.putString(getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                    "com.ha.auto_skip/com.ha.auto_skip.service.SkipService");

            Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED, 1);
        } catch (Exception e) {
            MyToast.warn("请用命令申请权限！");
            // adb shell pm grant com.ha.auto_skip android.permission.WRITE_SECURE_SETTINGS
        }

        initBindWidget();
        initSetListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initLoadData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.json) {
            startActivity(new Intent(this, JsonActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

    private void initBindWidget() {
        adapter = new JumpAdapter();
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.addItemDecoration(new SpacesItemDecoration(0, 18, 4, 18));
        binding.recyclerView.setAdapter(adapter);
    }

    private void initSetListener() {
        binding.add.setOnClickListener(view -> mActivityResultLauncher.launch(new Intent(this, AppListActivity.class)));

        binding.set.setOnClickListener(view -> {
            // 设置权限
            startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
        });

        adapter.setOnItemClickListener((view, viewType, data, position) -> {
            new SystemDialog.Builder(this)
                    .setCancelable(true)
                    .setMessage("请选择您的操作（点击返回按钮取消）")
                    .setNegativeButton("删除", (builder, view1) -> {
                        new SystemDialog.Builder(this)
                                .setTitle("提示")
                                .setMessage("删除操作不可逆，是否继续？")
                                .setNegativeButton("取消", null)
                                .setPositiveButton("删除", (builder1, view2) -> {
                                    adapter.removeItem(position);
                                    App.getJumpListBean().getJumpList().remove(position);
                                    App.getJumpListBean().saveAsJson();
                                })
                                .show();
                    })
                    .setPositiveButton("编辑", (builder, view12) -> {
                        edit(false, data, position);
                    })
                    .show();
        });
        mActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getData() != null) {
                        JumpBean bean = new JumpBean(
                                result.getData().getStringExtra("appName"),
                                result.getData().getStringExtra("appPackage")
                        );
                        edit(true, bean, 0);
                    }
                });

        binding.saveDuration.setOnClickListener(view -> {
            if (TextUtils.isEmpty(binding.clickDuration.getText().toString())) {
                MyToast.error("你在搞笑吗？时间不能为空");
                return;
            }
            try {
                App.setClickDuration(Long.parseLong(binding.clickDuration.getText().toString()));
                MyToast.success("保存成功");
            } catch (Exception e) {
                MyToast.error("你在搞笑吗？请输入正确时间");
            }
        });
    }

    private void initLoadData() {
        binding.clickDuration.setText(String.valueOf(App.getClickDuration()));
        adapter.reloadData(App.getJumpListBean().getJumpList());
    }

    /**
     * 新增一个
     *
     * @param bean
     */
    private void edit(boolean add, JumpBean bean, int position) {
        new InputDialog.Builder(this)
                .setData(bean)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", (key, fuzzy) -> {
                    bean.setKey(key);
                    bean.setFuzzy(fuzzy);

                    if (add) {
                        App.getJumpListBean().getJumpList().add(bean);
                        adapter.addItem(bean);
                    } else {
                        adapter.notifyItemChanged(position);
                    }
                    App.getJumpListBean().saveAsJson();
                })
                .show();
    }

}